import 'dart:async';
import 'dart:ui';

import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_learn_vi/src/bean/bean_user.dart';
import 'package:flutter_learn_vi/src/net/dio_utils.dart';
import 'package:flutter_learn_vi/src/page/common/user_protocol_page.dart';
import 'package:flutter_learn_vi/src/utils/log_util.dart';
import 'package:flutter_learn_vi/src/utils/navigator_utils.dart';
import 'package:flutter_learn_vi/src/utils/toast_utils.dart';

import 'bubble_login_page.dart';

/// 创建人： Created by zhaolong
/// 创建时间：Created by  on 2020/11/22.
///
/// 可关注公众号：我的大前端生涯   获取最新技术分享
/// 可关注网易云课堂：https://study.163.com/instructor/1021406098.htm
/// 可关注博客：https://blog.csdn.net/zl18603543572
/// 西瓜视频 https://www.ixigua.com/home/3662978423
/// 知乎 https://www.zhihu.com/people/zhao-long-90-89
///
///
/// 气泡背景的登录页面

//伯方App使用登录页面
class BoFangRegisterPage extends StatefulWidget {
  @override
  _BobbleRegisterPageState createState() => _BobbleRegisterPageState();
}

class _BobbleRegisterPageState extends State<BoFangRegisterPage>
    with TickerProviderStateMixin, WidgetsBindingObserver {
  @override
  void initState() {
    super.initState();
    //添加监听
    WidgetsBinding.instance.addObserver(this);

    // _userNameController.text = "ceshi1";
    // _passwordController.text = "123456";
  }

  @override
  void dispose() {
    //解绑
    WidgetsBinding.instance.removeObserver(this);
    super.dispose();
  }

  bool _showInputBg = false;

  //应用尺寸改变时回调
  @override
  void didChangeMetrics() {
    super.didChangeMetrics();
    /*
     *Frame是一次绘制过程，称其为一帧，
     * Flutter engine受显示器垂直同步信号"VSync"的驱使不断的触发绘制，
     *Flutter可以实现60fps（Frame Per-Second），
     * 就是指一秒钟可以触发60次重绘，FPS值越大，界面就越流畅。
     */
    WidgetsBinding.instance.addPostFrameCallback((_) {
      //注意，不要在此类回调中再触发新的Frame，这可以会导致循环刷新。
      setState(() {
        ///获取底部遮挡区域的高度
        double keyboderFlexHeight = MediaQuery.of(context).viewInsets.bottom;
        print("键盘的高度 keyboderFlexHeight $keyboderFlexHeight");
        if (MediaQuery.of(context).viewInsets.bottom == 0) {
          //关闭键盘 启动logo动画反向执行 0.0 -1.0
          // logo 布局区域显示出来
          setState(() {
            _showInputBg = false;
          });
        } else {
          //显示键盘 启动logo动画正向执行 1.0-0.0
          // logo布局区域缩放隐藏
          setState(() {
            _showInputBg = true;
          });
        }
      });
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: Colors.white,

      ///填充布局
      body: Container(
        width: MediaQuery.of(context).size.width,
        height: MediaQuery.of(context).size.height,
        child: Stack(
          children: [
            //第一部分 第一层 渐变背景
            //buildBackground(),
            //第二部分 第二层 气泡
            // BubbleWidget(),
            //第三部分 高斯模糊
            buildBlureWidget(),
            //第五部分 输入框与按钮
            buildColumn(context),
            //第六部分 左上角的关闭按钮
            buildCloseButton(context)
          ],
        ),
      ),
    );
  }

  Positioned buildCloseButton(BuildContext context) {
    return Positioned(
      top: 44,
      left: 10,
      child: CloseButton(
        onPressed: () {
          Navigator.of(context).pop();
        },
      ),
    );
  }

  Widget buildHeroLogo(BuildContext context) {
    return Row(
      crossAxisAlignment: CrossAxisAlignment.center,
      children: [
        Hero(
          tag: "loginTag",
          child: Material(
            color: Colors.transparent,
            child: ClipOval(
              child: InkWell(
                onTap: () {
                  Navigator.of(context).pop();
                },
                child: Image.asset(
                  "assets/images/2.0x/app_icon.png",
                  fit: BoxFit.fill,
                  width: 44,
                  height: 44,
                ),
              ),
            ),
          ),
        ),
        SizedBox(
          width: 16,
        ),
        Text(
          '欢迎登录',
          textAlign: TextAlign.center,
          style: TextStyle(
            color: Colors.blue,
            fontSize: 33.0,
            fontWeight: FontWeight.w600,
          ),
        ),
      ],
    );
  }

  //第一部分 第一层 渐变背景
  Widget buildBackground() {
    return Positioned.fill(
      child: Container(
        decoration: BoxDecoration(
          //线性渐变
          gradient: LinearGradient(
            //渐变角度
            begin: Alignment.topLeft,
            end: Alignment.bottomRight,
            //渐变颜色组
            colors: [
              Colors.lightBlue.withOpacity(0.3),
              Colors.lightBlueAccent.withOpacity(0.3),
              Colors.blue.withOpacity(0.3),
            ],
          ),
        ),
      ),
    );
  }

  //第三部分 高斯模糊
  Widget buildBlureWidget() {
    return Positioned.fill(
      child: BackdropFilter(
        filter: ImageFilter.blur(sigmaX: 0.3, sigmaY: 0.3),
        child: Container(
          color: Colors.white.withOpacity(0.1),
        ),
      ),
    );
  }

  //文本输入框控制器
  TextEditingController _userNameController = TextEditingController();
  TextEditingController _passwordController = TextEditingController();

  //焦点控制器
  FocusNode _userNameFocusNode = new FocusNode();
  FocusNode _passwordFocusNode = new FocusNode();
  bool _passwordIvi = true;
  StreamController<String> _passwordStreamController = new StreamController();

  //第五部分 输入框与按钮
  Widget buildColumn(BuildContext context) {
    return Positioned.fill(
      child: GestureDetector(
        onTap: () {
          hidenKeyBoard();
        },
        child: Container(
          color:
              _showInputBg ? Colors.white.withOpacity(0.9) : Colors.transparent,
          padding: EdgeInsets.all(44),
          child: buildInputColumn(context),
        ),
      ),
    );
  }

  //是否选中用户协议
  bool _isProtocol = false;

  Widget buildInputColumn(BuildContext context) {
    return SingleChildScrollView(
      child: Column(
        //子Widget 底部对齐
        mainAxisAlignment: MainAxisAlignment.start,
        children: <Widget>[
          SizedBox(
            height: 80,
          ),
          //第四部分 顶部的文字 logo 的Hero动画
          buildHeroLogo(context),
          SizedBox(
            height: 80,
          ),
          TextFieldWidget(
            hintText: '手机号',
            focusNode: _userNameFocusNode,
            controller: _userNameController,
            obscureText: false,
            prefixIconData: Icons.mail_outline,
            submit: (String value) {
              checkUserName(value);
              //焦点切换
              _userNameFocusNode.unfocus();
              FocusScope.of(context).requestFocus(_passwordFocusNode);
            },
          ),
          SizedBox(
            height: 10.0,
          ),
          Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: <Widget>[
              Stack(
                children: [
                  TextFieldWidget(
                    hintText: '验证码',
                    controller: _passwordController,
                    focusNode: _passwordFocusNode,
                    obscureText: false,
                    prefixIconData: Icons.cloud_circle_outlined,
                    submit: (String value) {
                      checkPassword(value);
                      submitLoginFunction();
                    },
                  ),
                  Positioned(
                    child: TextButton(
                      onPressed: () {
                        bool flag = checkUserName(_userNameController.text);
                        if (flag) {
                          if (_timer != null && _timer.isActive) {
                            ToastUtils.showToast("验证码已发送");
                            return;
                          }
                          startTimer();
                        }
                      },
                      child: StreamBuilder<String>(
                        initialData: _codeButtonText,
                        stream: _passwordStreamController.stream,
                        builder: (BuildContext context,
                            AsyncSnapshot<String> snapshot) {
                          return Text("${snapshot.data}");
                        },
                      ),
                    ),
                    right: 8,
                  )
                ],
              ),
              SizedBox(
                height: 10.0,
              ),
              SizedBox(
                height: 10.0,
              ),
              Row(
                children: [
                  Checkbox(
                    value: _isProtocol,
                    onChanged: (bool value) {
                      setState(() {
                        _isProtocol = value;
                      });
                    },
                  ),
                  InkWell(
                    onTap: () {
                      showUserProtocolPage(
                          context: context, isOneButton: true, rightText: "同意");
                    },
                    child: Text(
                      '登录即代表同意用户协议',
                      style: TextStyle(
                        color: _isProtocol
                            ? Theme.of(context).accentColor
                            : Colors.grey,
                      ),
                    ),
                  ),
                ],
              ),
            ],
          ),
          SizedBox(
            height: 20.0,
          ),
          Container(
            width: double.infinity,
            height: 60,
            child: ElevatedButton(
              onPressed: () {
                submitLoginFunction();
              },
              child: Text(
                "登录",
                style: TextStyle(fontSize: 18, color: Colors.white),
              ),
            ),
          ),
          Container(
            width: double.infinity,
            margin: EdgeInsets.only(top: 10),
            height: 60,
          ),
        ],
      ),
    );
  }

  ///登录
  void submitLoginFunction() async {
    //隐藏键盘
    hidenKeyBoard();

    if (!_isProtocol) {
      ToastUtils.showToast("请选择同意用户协议");
      return;
    }

    //获取用户输入的内容
    String userName = _userNameController.text.trim();
    String password = _passwordController.text.trim();

    //校验
    checkUserName(userName);
    checkPassword(password);

    //参数封装
    Map<String, String> map = new Map();
    map["mobile"] = userName;
    map["password"] = password;
    //post请求发送
    ResponseInfo responseInfo = await DioUtils.instance.postRequest(
      url: HttpHelper.UWER_Register_URL,
      jsonMap: map,
    );
    //登录成功
    if (responseInfo.success) {
      ToastUtils.showToast("登录成功");
      await Future.delayed(Duration(milliseconds: 1200), () {});
      NavigatorUtils.pop(context, parameters: map);
    } else {
      //登录失败
      ToastUtils.showToast(responseInfo.message);
    }
  }

  void checkPassword(String value) {
    if (value.trim().length == 0) {
      ToastUtils.showToast("请输入验证码");
      return;
    }
  }

  bool checkUserName(String value) {
    if (value.trim().length != 11) {
      ToastUtils.showToast("请输入11位手机号");
      return false;
    }
    return true;
  }

  void hidenKeyBoard() {
    //隐藏键盘
    SystemChannels.textInput.invokeMethod('TextInput.hide');
    _passwordFocusNode.unfocus();
    _userNameFocusNode.unfocus();
  }

  Future<UserBean> selectUserBeanFunction(List<UserBean> userList) async {
    return showDialog(
        context: context,
        barrierDismissible: true,
        builder: (BuildContext context) {
          return AlertDialog(
            content: Container(
              height: 200,
              width: MediaQuery.of(context).size.width,
              child: ListView.builder(
                itemBuilder: (BuildContext context, int index) {
                  UserBean userBean = userList[index];
                  return ListTile(
                    title: Text(userBean.mineName),
                    onTap: () {
                      Navigator.of(context).pop(userBean);
                    },
                  );
                },
                itemCount: userList.length,
              ),
            ),
          );
        });
  }

  Timer _timer;
  String _codeButtonText = '获取验证码';
  int _total = 5;
  int _current = 0;

  void startTimer() {
    _timer = Timer.periodic(Duration(milliseconds: 1000), (va) {
      _current = _current + 1;
      int flag = _total - _current;
      String message = "$flag秒后重新获取";
      if (flag <= 0) {
        _timer.cancel();
        _timer = null;
        _current = 0;
        message = "获取验证码";
      }
      LogUtils.e("计时");
      _passwordStreamController.add(message);
    });
  }
}
